package com.vnp.vchat.version2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.telpoo.frame.delegate.Idelegate;
import com.telpoo.frame.utils.Mlog;
import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.UIControls.MyCircleImageView;
import com.vnp.vchat.adapter.ChatAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.bean.ObjMsgChat;
import com.vnp.vchat.database.DBAdapter;
import com.vnp.vchat.database.DBFunction;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.DecodeUtils;
import com.vnp.vchat.util.Dl;
import com.vnp.vchat.util.KeyboardHelper;
import com.vnp.vchat.util.MyDialog;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;

public class ChatNewActivity extends Activity implements OnTouchListener, OnClickListener, OnItemClickListener, Idelegate {
	MediaPlayer mpVoice;
	MySQLiteHelper db;
	PreferenceHelper preferenceHelper;
	ImageView btnBack;

	ProgressBar progressBar;
	private  String hashChat = null;
	String namechat;
	ViewGroup header;
	int currentLvHeight = 0;
	boolean onPause = false;
	boolean onFinish = false;
	boolean isNoti = false;
	public static boolean onShow;
	TextView txtSanpham;
	String url = "", dsDaxem;

	boolean isNew = false;

	boolean isFirstTime = true;

	byte[] byteArray1;
	String status = "";

	boolean isShowingBtnNew = false;

	// msg ko phai cua minh
	LinearLayout llNewMsg;
	TextView txtTen, txtMsg;
	Animation pullDown, pullUp;// , fadeIn, fadeOut;

	Runnable rHide = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					llNewMsg.setVisibility(View.GONE);
					llNewMsg.startAnimation(pullUp);
				}
			});

		}
	};

	Runnable autogetHistory = new Runnable() {

		@Override
		public void run() {

			getHistorychat(hashChat);
			mHandler.removeCallbacks(autogetHistory);
			mHandler.postDelayed(autogetHistory, 5000);

		}
	};

	void startGetHistory() {
		mHandler.removeCallbacks(autogetHistory);
		mHandler.postDelayed(autogetHistory, 5000);
	}

	Runnable rShowDangxuat = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					llDangxuat.setVisibility(View.VISIBLE);
				}
			});

		}
	};

	Runnable rHideDangxuat = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					llDangxuat.setVisibility(View.GONE);
				}
			});

		}
	};

	Runnable rEnableSend = new Runnable() {

		@Override
		public void run() {
			btnSend.setEnabled(true);
		}
	};

	Runnable rUpdateSeekbar = new Runnable() {

		@Override
		public void run() {
			updateSeekBar();
			mHandler.postDelayed(rUpdateSeekbar, 1000);
		}
	};

	MediaPlayer mp;

	String ten;
	TextView title;
	ListView listChat;
	FrameLayout main;
	ChatAdapter adapter;

	// layout chat
	EditText edtChat;
	ImageButton btnChupanh;
	Button btnSend;
	ImageView btnClear;

	Handler mHandler = new Handler();

	String KEY_SOFTWARE = "kksdfuy97dfsdfjh23uibjdbsjfsdf";

	String tokenChuaMd5, tokenMd5;

	ObjKhachhang objKhachhang = new ObjKhachhang();

	ViewGroup llDangxuat;
	TextView txtDangxuat;
	Thread tr;
	Runnable rDangxuat = new Runnable() {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					llDangxuat.setVisibility(View.GONE);
				}
			});

		}
	};

	// Runnable rHis1 = new Runnable() {
	//
	// @Override
	// public void run() {
	// getHash();
	// }
	// };

	ViewGroup llChat;
	TextView llChatDis;
	private BroadcastReceiver mReceiver;

	// layout new msg khi dang cuon len tren
	LinearLayout llNewMsgTop;
	private boolean isLastestMsg = false;

	// show dialog chon anh
	Dialog dChoose;

	// chon anh
	private static final int RESULT_PICK_PHOTO = 100;
	private static final int RESULT_CAPTURE_PHOTO = 200;
	private static final int RESULT_RECORD = 201;

	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;

	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_take_photo.jpg";
	// String file_path;

	DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Config.RGB_565)
			.showImageForEmptyUri(R.drawable.defaul_avatar).build();

	View h;
	TextView titleP;
	MyCircleImageView imgAvatar;

	DBFunction dbf;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat_new);

		if (savedInstanceState != null) {
			mCapturedImageURI = Uri.parse("" + savedInstanceState.getString("uri"));
		}

		dbf = new DBFunction(DBAdapter.getObj(this));
		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(ChatNewActivity.this);
		isFirstTime = true;
		main = (FrameLayout) findViewById(R.id.main);
		KeyboardHelper.setupUI(ChatNewActivity.this, main);
		objKhachhang = getIntent().getParcelableExtra("khachhang");

		// xac dinh la dang o man hinh chat
		Common.onScreenChat = true;
		Common.isChatting = objKhachhang.getId();

		preferenceHelper.setAvatarKH(objKhachhang.getUrlAvatar());

		MD5Token();
		// update tin nhan cuoi la da doc

		db.updateLastMsgDadoc(objKhachhang.getId(), 0);

		url = objKhachhang.getUrlDangxem();
		dsDaxem = objKhachhang.getDsDaxem();

		title = (TextView) findViewById(R.id.title);
		title.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this), Typeface.BOLD);
		btnBack = (ImageView) findViewById(R.id.btn_back);
		// btnBack.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this),
		// Typeface.BOLD);
		Utils.HightImageview(btnBack);
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);

		llChat = (ViewGroup) findViewById(R.id.ll_chat);
		llChat.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				isLastestMsg = true;
				goToLastestMsg();
				return false;
			}
		});
		llChatDis = (TextView) findViewById(R.id.ll_chat_dis);

		// check on off
		llDangxuat = (ViewGroup) findViewById(R.id.ll_dangxuat);
		txtDangxuat = (TextView) findViewById(R.id.txt_kh_dangxuat);
		// new msg khi khong o cuoi doan chat
		llNewMsgTop = (LinearLayout) findViewById(R.id.ll_tinnhan_moi);

		// header
		h = findViewById(R.id.ll_product);
		titleP = (TextView) findViewById(R.id.titleP);
		imgAvatar = (MyCircleImageView) findViewById(R.id.avatar_khach_hang);
		txtSanpham = (TextView) findViewById(R.id.txt_sanpham);
		header = (ViewGroup) findViewById(R.id.header);
		if (objKhachhang.getDsDaxem() == null || objKhachhang.getDsDaxem().equals("")) {
			header.setVisibility(View.GONE);

		} else {
			header.setVisibility(View.VISIBLE);
		}
		btnBack.setVisibility(View.VISIBLE);

		// new msg ko phai cua mình
		llNewMsg = (LinearLayout) findViewById(R.id.ll_new_msg);
		txtTen = (TextView) findViewById(R.id.txt_name);
		txtMsg = (TextView) findViewById(R.id.txt_msg);

		pullDown = AnimationUtils.loadAnimation(this, R.anim.slide_down);
		pullUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);
		// fadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
		// fadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);

		mp = MediaPlayer.create(ChatNewActivity.this, R.raw.result);

		// layout chat
		btnChupanh = (ImageButton) findViewById(R.id.btn_chupanh);
		edtChat = (EditText) findViewById(R.id.edt_chat);
		btnSend = (Button) findViewById(R.id.btn_send);
		btnClear = (ImageView) findViewById(R.id.btn_clears);

		listChat = (ListView) findViewById(R.id.list_chat);
		addBlankItem();
		addHeader();

		adapter = new ChatAdapter(ChatNewActivity.this, R.layout.item_chat, new ArrayList<ObjMsgChat>());
		listChat.setAdapter(adapter);

		listChat.setOnItemClickListener(this);

		goToLastestMsg();

		showProgressBar();
		forceHiddenProgressBar();

		setUpEditor();
		initAction();
		reciveBroadCast();
		setFont();

		runGetHash();
		ViewTreeObserver observer = listChat.getViewTreeObserver();
		observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@Override
			public void onGlobalLayout() {
				if (listChat.getHeight() - currentLvHeight != 0) {

					isLastestMsg = true;
					goToLastestMsg();
				}
				currentLvHeight = listChat.getHeight();

			}
		});

		updateListview();

		adapter.setDelegate(this);

	}

	@SuppressLint("NewApi")
	protected void updateSeekBar() {

		if (mpVoice != null) {
			try {
				if (mpVoice.isPlaying()) {
					currSB.setProgress(mpVoice.getCurrentPosition());
					int duation = mpVoice.getDuration() - mpVoice.getCurrentPosition();
					currTimePlay.setText(Utils.fomatTime(duation));

				}

			} catch (Exception e) {
			}
		}

	}

	Runnable getHashRunnable = new Runnable() {

		@Override
		public void run() {
			getHash();
		}
	};

	void runGetHash() {
		mHandler.removeCallbacks(getHashRunnable);
		mHandler.postDelayed(getHashRunnable, 500);
	}

	void runGetHash(int timeDelay) {
		mHandler.removeCallbacks(getHashRunnable);
		mHandler.postDelayed(getHashRunnable, timeDelay);
	}

	private void MD5Token() {
		tokenChuaMd5 = KEY_SOFTWARE + "|" + preferenceHelper.getAdminId() + "|" + objKhachhang.getId();
		tokenMd5 = Utils.MD5(tokenChuaMd5);
	}

	private void showAnimationNewMsg() {
		llNewMsg.setVisibility(View.VISIBLE);
		llNewMsg.startAnimation(pullDown);
		// mHandler.removeCallbacks(rShow);
		// mHandler.postDelayed(rShow, 1000);
		mHandler.removeCallbacks(rHide);
		mHandler.postDelayed(rHide, 3000);
	}

	private void playRingtone() {
		try {
			// mp.reset();
			mp.prepare();
			mp.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void addBlankItem() {
		LayoutInflater inflater = getLayoutInflater();
		View v = inflater.inflate(R.layout.header_blank, listChat, false);
		// listChat.addHeaderView(v, null, false);
	}

	private void addHeader() {
		if (!url.equals("")) {
			if (objKhachhang.getDsDaxem().equals("")) {
				if (url.length() > 30) {
					txtSanpham.setText(url.substring(0, 30) + "...");
				} else {
					txtSanpham.setText(url);
				}
			} else {
				if (dsDaxem.length() > 40) {
					txtSanpham.setText(dsDaxem.substring(0, 37) + "...");
				} else {
					txtSanpham.setText(dsDaxem);
				}
			}
		} else {
			txtSanpham.setText("Chưa xem sản phẩm.");
		}

		ImageLoader.getInstance().displayImage(objKhachhang.getUrlAvatar(), imgAvatar, options);

		titleP.setTypeface(Utils.getTypefaceMedium(ChatNewActivity.this));
		txtSanpham.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));

		h.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!url.equals("")) {
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(browserIntent);
				}
			}
		});
	}

	private void setUpEditor() {
		edtChat.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
				if (s.toString().length() > 0) {
					btnClear.setVisibility(View.VISIBLE);
				} else {
					btnClear.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});

		edtChat.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				actionSend();
				return true;
			}
		});

	}

	void actionSend() {
		String msgId = String.valueOf(Common.getCurrentTime() / 1000);
		String lastMsg = edtChat.getText().toString();

		if (lastMsg != null && !lastMsg.equals("")) {
			edtChat.setText("");
			// ObjMsgChat objMsgChat = new
			// ObjMsgChat(preferenceHelper.getAdminId(), "", lastMsg, "");
			ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(), "", lastMsg, "", preferenceHelper.getUserName(), preferenceHelper.getMyAvatar(),
					preferenceHelper.getLink());
			objMsgChat.setMsgID(msgId);
			objMsgChat.setType("text");
			objMsgChat.setStatus(Common.SENDING);
			objMsgChat.setTime((Common.getCurrentTime() / 1000));

			objKhachhang.setLastMessage(lastMsg);
			objKhachhang.setTimeLastMessage("" + (Common.getCurrentTime() / 1000));
			dbf.insertMSG(objMsgChat, objKhachhang.getId(), Common.SENDING, msgId, ChatNewActivity.this);
			updateListview();
			db.updateHischat(objKhachhang);
			btnSend.setEnabled(false);
			mHandler.postDelayed(rEnableSend, 1000);
			sendMsgToServer(objKhachhang.getId(), objMsgChat);
		}
	}

	private void setFont() {
		edtChat.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		btnSend.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtMsg.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtTen.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		txtDangxuat.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
	}

	private void initAction() {

		listChat.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem + visibleItemCount < totalItemCount) {
					isLastestMsg = false;
				} else {
					isLastestMsg = true;
					hiddenButtonLastestMsg();
				}

			}
		});

		title.setText(objKhachhang.getName());

		btnBack.setOnTouchListener(this);
		edtChat.setOnTouchListener(this);
		btnClear.setOnClickListener(this);
		btnSend.setOnClickListener(this);
		btnChupanh.setOnClickListener(this);
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				closeActivity();
			}

		case R.id.edt_chat:

			if (event.getAction() == MotionEvent.ACTION_UP) {
				isLastestMsg = true;
				goToLastestMsg();
				edtChat.requestFocus();
				edtChat.setFocusable(true);
			}
		default:
			break;
		}
		return false;
	}

	void closeActivity() {
		finish();
		onShow = true;
		overridePendingTransition(0, R.anim.trans_right_out);
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_clears:
			edtChat.setText("");
			break;

		case R.id.btn_send:
			actionSend();
			btnSend.setEnabled(false);
			break;
		case R.id.btn_chupanh:
			showDialogChonanh();
			break;

		case R.id.btn_capture_image:
			dChoose.dismiss();
			takeImage();
			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_thoat:
			dChoose.dismiss();
			break;
		case R.id.btn_goi_thoai:
			// MyDialog.showgoithoai(ChatNewActivity.this, new Idelegate() {
			//
			// @Override
			// public void callBack(Object value, int where) {
			// String mpString = (String) value;
			// addLinkAudio("" + mpString);
			// }
			// });
			// dChoose.dismiss();
			dChoose.dismiss();
			Intent in = new Intent(ChatNewActivity.this, MyDialog.class);
			startActivityForResult(in, RESULT_RECORD);
			break;
		default:
			break;
		}
	}

	private void addMsgImage(String url) {
		String msgId = String.valueOf(Common.getCurrentTime() / 1000);
		// ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(),
		// "", "", url);
		ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(), "", "", url, preferenceHelper.getUserName(), preferenceHelper.getMyAvatar(),
				preferenceHelper.getLink());
		objMsgChat.setType("image");
		objMsgChat.setStatus(Common.SENDING);
		objMsgChat.setMsgID(msgId);
		// objMsgChat.setVgc_key(msgId);
		objMsgChat.setTime(Common.getCurrentTime() / 1000);

		goToLastestMsg();

		dbf.insertMSG(objMsgChat, objKhachhang.getId(), Common.SENDING, msgId, ChatNewActivity.this);
		btnSend.setEnabled(false);
		mHandler.postDelayed(rEnableSend, 700);
		updateListview();
		uploadImage(objMsgChat);
	}

	boolean ischeck = false;
	private boolean isFirstChat = false; // neu la chat lan dau
	private int curPosPlay = -1;
	private SeekBar currSB;
	private TextView currTimePlay;
	private int lastDuration;
	private ImageView currBtnPlay;

	private void getHistorychat(String hash) {

		preferenceHelper.setTimeGetHistory();

		if (hash == null) {
			Mlog.E("getHistorychat hash=null");
			return;
		}

		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback() {

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200) {
					try {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								progressBar.setVisibility(View.GONE);
							}
						});

						int status = re.getInt("status");
						if (status == 1) {
							// dbf.deteleAllRecord(objKhachhang.getId());
							JSONArray listMsg = re.getJSONArray("msg");

							for (int i = 0; i < listMsg.length(); i++) {
								JSONObject msg = listMsg.getJSONObject(i);
								int fromTo = msg.getInt("cha_owner_id");
								String contentMsg = msg.getString("cha_message");

								String msgID = msg.getString("cha_key");

								String time = msg.getString("cha_time");
								if (msgID.equals("0")) {
									msgID = time + objKhachhang.getId();
								}
								final ObjMsgChat objMsgChat = new ObjMsgChat();
								// objMsgChat.setVgc_key(msgID);
								if (msg.has("type")) {
									if (msg.getString("type").equals("image")) {
										objMsgChat.setUrlImageKH(contentMsg);
										objMsgChat.setType("image");
									} else {
										objMsgChat.setUrlImageKH("");
										objMsgChat.setType("text");
									}
								} else {
									objMsgChat.setUrlImageKH("");
									objMsgChat.setType("text");
								}

								objMsgChat.setMsgID(msgID);
								objMsgChat.setUrlAvatarKhachhang(objKhachhang.getUrlAvatar());
								objMsgChat.setFromId(String.valueOf(fromTo));
								objMsgChat.setContent(contentMsg);
								objMsgChat.setTime(Integer.valueOf(time));
								objMsgChat.setTenKhachHang(objMsgChat.getTenKhachHang());
								objMsgChat.setStatus(1);

								dbf.insertMSG(objMsgChat, objKhachhang.getId(), 1, objMsgChat.getMsgID(), ChatNewActivity.this);

							}

						} else {
							Log.i("vChat", "ERROR: " + re.toString());
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									progressBar.setVisibility(View.INVISIBLE);
								}
							});
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
						}
					});
				}

				updateListview();

			}

			@Override
			public void onFailure(Exception e) {
			}
		});

		Integer khachid = null;
		try {
			khachid = Integer.valueOf(objKhachhang.getId());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (khachid == null) {
			Toast.makeText(getBaseContext(), "Không lấy được id khách hàng này!", 1).show();
			finish();
			return;
		}

		httpBasicClientHelper.getHistoryChat(Integer.valueOf(preferenceHelper.getAdminId()), khachid, hash, 1, 1);
	}

	private void getHash() {

		Mlog.D("getHash()");
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback() {

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200) {
					try {
						String error = re.getString("error");
						Log.i("vChat", "HASH: " + re.toString());
						if (!error.equals("")) {
							Log.i("hash", "get hashChat fail");
							runGetHash(2000);

							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									String ck = com.telpoo.frame.utils.Utils.getStringSPR("regethash", ChatNewActivity.this);
									if (!"1".equals(ck))
										Toast.makeText(ChatNewActivity.this, "Không kết nối được với máy chủ.", Toast.LENGTH_SHORT).show();
									com.telpoo.frame.utils.Utils.saveStringSPR("regethash", "1", ChatNewActivity.this);
								}
							});

						} else {
							hashChat = re.getString("hash");

							namechat = re.getString("name");

							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									title.setText(namechat);
									String ck = com.telpoo.frame.utils.Utils.getStringSPR("regethash", ChatNewActivity.this);
									if ("1".equals(ck))
										Toast.makeText(ChatNewActivity.this, "Đã kết nối thành công", Toast.LENGTH_SHORT).show();
									com.telpoo.frame.utils.Utils.saveStringSPR("regethash", "0", ChatNewActivity.this);
								}
							});

							Mlog.D("HASH CHAT: " + hashChat);
							getHistorychat(hashChat);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
				}
			}

			@Override
			public void onFailure(Exception e) {
				Log.i("hash", "get hashChat fail");
				runGetHash(2000);

				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						String ck = com.telpoo.frame.utils.Utils.getStringSPR("regethash", ChatNewActivity.this);
						if (!"1".equals(ck))
							Toast.makeText(ChatNewActivity.this, "Không kết nối được với máy chủ.", Toast.LENGTH_SHORT).show();
						com.telpoo.frame.utils.Utils.saveStringSPR("regethash", "1", ChatNewActivity.this);
					}
				});
			}
		});
		Mlog.D("get hash objKhachhang.getId()=" + objKhachhang.getId() + " preferenceHelper.getAdminId()=" + preferenceHelper.getAdminId());
		Integer khachid = null;
		try {
			khachid = Integer.valueOf(objKhachhang.getId());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (khachid == null) {
			Toast.makeText(getBaseContext(), "Không lấy được id khách hàng này!", 1).show();
			finish();
			return;
		}
		httpBasicClientHelper.getHash(khachid, Integer.valueOf(preferenceHelper.getAdminId()), preferenceHelper.getHashSetting(), 1);
		// } else {
		// getHistorychat(hashChat);
		// }
	}

	public String sendMsgToServer(String _kh_id, final ObjMsgChat oMsg) {

		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback() {

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200) {
					Log.i("vChat", "SENDMSG: " + re.toString());
					try {
						String error = re.getString("error");
						if (error.equals("")) {

							Log.i("SendMSG", "Gui thanh cong");
							status = "1";
							oMsg.setStatus(1);
						} else {
							status = "0";
							oMsg.setStatus(2);
							Log.i("SendMSG", "Chua gui dc tin nhan");
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									Toast.makeText(ChatNewActivity.this, "Chưa gửi được tin nhắn.", Toast.LENGTH_SHORT).show();
								}
							});
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					oMsg.setStatus(2);
				}
				dbf.updateStatusMsg(oMsg.getMsgID(), oMsg.getStatus());
				isLastestMsg = true;
				updateListview();
				// notifiDataChange();
			}

			@Override
			public void onFailure(Exception e) {
				oMsg.setStatus(2);
				dbf.updateStatusMsg(oMsg.getMsgID(), oMsg.getStatus());
				isLastestMsg = true;
				updateListview();
			}

		});

		if (adapter.getCount() > 3)
			isFirstChat = false;
		else
			isFirstChat = true;

		httpBasicClientHelper.sendChatMsg(Integer.valueOf(preferenceHelper.getAdminId()), Integer.valueOf(_kh_id), hashChat, "text", 1, oMsg.getContent(),
				preferenceHelper.getUserName(), oMsg.getMsgID(), oMsg.getMsgID(), isFirstChat, preferenceHelper.getMyAvatar());
		Log.i("DATA", "VGC gui di : " + oMsg.getMsgID());
		// Common.VGC = oMsg.getMsgID();

		return status;
	}

	protected void updateListview() {
		ArrayList<ObjMsgChat> ab = dbf.getAllMsgHis(objKhachhang.getId());
		// Mlog.T("updateListview 0="+ab.get(0).getContent());
		// Mlog.T("updateListview n="+ab.get(ab.size()-1).getContent());
		adapter.SetItems(ab);
		goToLastestMsg();
	}

	private void sendMsgImage(String url, final ObjMsgChat oMsg) {

		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback() {

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200) {
					try {
						final String error = re.getString("error");
						if (error.equals("")) {
							Log.i("SendMSG", "Gui thanh cong");
							status = "1";
							oMsg.setStatus(1);
						} else {
							status = "0";
							oMsg.setStatus(2);
							Log.i("SendMSG", "Chua gui dc tin nhan");
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									Toast.makeText(ChatNewActivity.this, "Chưa gửi được tin nhắn." + error, Toast.LENGTH_SHORT).show();
								}
							});

						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					oMsg.setStatus(2);
				}
				dbf.updateStatusMsg(oMsg.getMsgID(), oMsg.getStatus());

				updateListview();
			}

			@Override
			public void onFailure(Exception e) {
				oMsg.setStatus(2);
				dbf.updateStatusMsg(oMsg.getMsgID(), oMsg.getStatus());
				updateListview();
			}

		});

		if (adapter.getCount() > 3)
			isFirstChat = false;
		else
			isFirstChat = true;

		httpBasicClientHelper.sendChatMsg(Integer.valueOf(preferenceHelper.getUserId()), Integer.valueOf(objKhachhang.getId()), hashChat, "image", 1, url, objKhachhang.getName(),
				oMsg.getMsgID(), oMsg.getMsgID(), isFirstChat, preferenceHelper.getMyAvatar());
		Log.i("DATA", "VGC gui di : " + oMsg.getMsgID());
		// Common.VGC = oMsg.getMsgID();
	}

	@Override
	protected void onPause() {
		stopPlay();
		super.onPause();
		Common.appRunning = false;
		disConnectSocketWhenAppPause();
		onPause = true;
		MainPanelActivity.isRunningApp = false;

	}

	private void disConnectSocketWhenAppPause() {
		if (!Common.appRunning) {
			if (MainPanelActivity.getInstance() != null) {
				MainPanelActivity.getInstance().stopAutoConnect();
				MainPanelActivity.getInstance().StopSocket();
			}
		}

	}

	private void connectSocketWhenAppResume() {
		if (Common.appRunning) {
			if (MainPanelActivity.getInstance() != null) {
				MainPanelActivity.getInstance().startSocket();
				MainPanelActivity.getInstance().startAutoConnect();
			}
		}

	}

	@Override
	protected void onStop() {
		super.onStop();

	}

	@Override
	protected void onResume() {
		super.onResume();
		Common.appRunning = true;
		onPause = false;
		MainPanelActivity.isRunningApp = true;
		connectSocketWhenAppResume();
		startGetHistory();

//		if (adapter.getCount() > 0) {
//
//			ObjMsgChat ckMsg = adapter.getItem(adapter.getCount() - 1);
//			if (ObjMsgChat.TYPE_IMAGE.equals(ckMsg.getType())) {
//				if (ckMsg.getStatus() != ObjMsgChat.STATUS_SUCCESS) { // chua up
//																		// thanh
//																		// cong
//					uploadImage(ckMsg);
//				}
//			}
//		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("vChat", "Trang thai destroy");
		cancelHandler();

		if (isNew == true) {
			Common.onScreenChat = true;
		} else {
			Common.isChatting = "";
			Common.onScreenChat = false;
		}

		onPause = true;
		unregisterReceiver(mReceiver);
	}

	private void cancelHandler() {
		mHandler.removeCallbacks(rHideDangxuat);
		mHandler.removeCallbacks(rShowDangxuat);
		mHandler.removeCallbacks(rDangxuat);
		// mHandler.removeCallbacks(rShow);
		mHandler.removeCallbacks(rHide);
		mHandler.removeCallbacks(rEnableSend);
		mHandler.removeCallbacksAndMessages(null);
	}

	private void reciveBroadCast() {
		IntentFilter intentFilter = new IntentFilter();

		intentFilter.addAction(Common.CHAT);
		intentFilter.addAction(Common.CHAT_NEWMSG);

		intentFilter.addAction(Common.CONNECTTING);
		intentFilter.addAction(Common.CONNECTED);

		intentFilter.addAction(Common.FINSH_CHAT);
		intentFilter.addAction(Common.CONNECT);
		intentFilter.addAction(Common.MY_ADD);
		intentFilter.addAction(Common.HAVE_MESSAGE);

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, final Intent intent) {
				String action = intent.getAction();
				if (action.equals(Common.CHAT)) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									if (!isLastestMsg) {
										showButtonLastestMsg();
										isShowingBtnNew = true;
										Log.i("DATA", "kieu tin nhan moi");
									} else {
										// objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
										adapter.notifyDataSetChanged();
										goToLastestMsg();
									}

								}
							});

							// adapter.notifyDataSetChanged();
						}
					});
					// Log.i("vChat", "Nhan duoc broadcast chat");
					Mlog.w("nhan duoc broad cast chat");
				} else if (action.equals(Common.CHAT_NEWMSG)) {
					// Log.i("vChat", "Nhan duoc broadcast chat new msg");
					Mlog.w("nhat duoc broadcast new msg");
					llNewMsg.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View view) {

							Log.i("vChat", "Trong man hinh chat click new msg");
							ChatNewActivity.onShow = true;
							isNew = true;
							ObjKhachhang objKhachhang = new ObjKhachhang();
							objKhachhang = intent.getParcelableExtra("khachhang");
							Intent t = new Intent(ChatNewActivity.this, ChatNewActivity.class);
							t.putExtra("khachhang", objKhachhang);
							finish();
							startActivity(t);
						}
					});

					runOnUiThread(new Runnable() {

						@Override
						public void run() {

							mHandler.removeCallbacks(rHide);
							// mHandler.removeCallbacks(rShow);

							if (llNewMsg.getVisibility() == View.VISIBLE) {
								llNewMsg.setVisibility(View.GONE);
							}

							showAnimationNewMsg();
							if (preferenceHelper.getSettingRingtone() == 1) {
								playRingtone();
							}
							ObjMsgChat objMsgChatNew = new ObjMsgChat();
							objMsgChatNew = intent.getParcelableExtra("objMsg");
							txtTen.setText(objMsgChatNew.getTenKhachHang());
							txtMsg.setText(objMsgChatNew.getContent());

						}
					});

				} else if (action.equals(Common.FINSH_CHAT)) {
					finish();
				} else if (action.equals(Common.CONNECT)) {

				} else if (action.equals(Common.MY_ADD)) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Log.i("DATA", "nhay vào để add tin nhắn trên nhiều thiết bị");
							// objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
							adapter.notifyDataSetChanged();
							goToLastestMsg();
						}
					});
				} else if (action.equals(Common.HAVE_MESSAGE)) {
					Log.i("Socket", "action.equals(Common.HAVE_MESSAGE)");

					String[] databroad = intent.getStringArrayExtra("data");
					onOfSocket(databroad[0], databroad[1]);
				}
			}
		};

		// register
		this.registerReceiver(mReceiver, intentFilter);
	}

	private void hiddenButtonLastestMsg() {
		isShowingBtnNew = false;
		llNewMsgTop.setVisibility(View.GONE);
	}

	private void showButtonLastestMsg() {
		llNewMsgTop.setVisibility(View.VISIBLE);
	}

	private void goToLastestMsg() {
		if (isLastestMsg) {
			listChat.post(new Runnable() {

				@Override
				public void run() {
					listChat.setSelection(adapter.getCount());
					// listChat.smoothScrollToPosition(listChat.getCount());

				}
			});
		}
	}

	// show dialog sau khi them thanh cong
	public void showDialogChonanh() {
		onShow = true;
		dChoose = new Dialog(this, R.style.DialogSlideAnim);
		dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dChoose.setContentView(R.layout.dialog_choose_photo);

		Button btnChonanh = (Button) dChoose.findViewById(R.id.btn_choose_image);
		Button btnChupanh = (Button) dChoose.findViewById(R.id.btn_capture_image);
		Button btn_goi_thoai = (Button) dChoose.findViewById(R.id.btn_goi_thoai);
		Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);

		btnChonanh.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		btnChupanh.setTypeface(Utils.getTypefaceRegular(ChatNewActivity.this));
		// btnThoat.setTypeface(Utils.getTypefaceBold(ChatActivity.this),
		// Typeface.BOLD);

		dChoose.show();
		dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dChoose.setCanceledOnTouchOutside(true);
		dChoose.getWindow().setGravity(Gravity.BOTTOM);
		dChoose.show();

		// setonclick
		btnChonanh.setOnClickListener(this);
		btnChupanh.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
		btn_goi_thoai.setOnClickListener(this);
	}

	// chon anh
	public void openGallery() {
		File ff = new File(TEMP_TAKE_IMAGE);
		if (ff.exists())
			ff.delete();
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, RESULT_PICK_PHOTO);
	}

	// chup anh
	public void takeImage() {
		String fileName = "temp.jpg";
		ContentValues values = new ContentValues();
		values.put(MediaColumns.TITLE, fileName);
		mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
		startActivityForResult(intent, RESULT_CAPTURE_PHOTO);
	}

	@SuppressLint("NewApi")
	@SuppressWarnings({ "deprecation", "unused" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RESULT_PICK_PHOTO:
				Uri u = data.getData();
				String[] filePathColumn = { MediaColumns.DATA };
				Cursor cursor = getContentResolver().query(u, filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String filePathPhoto;
				filePathPhoto = cursor.getString(columnIndex);
				Log.i("DATA", "File filePathPhoto :" + filePathPhoto);
				filePathPhoto = "file://" + filePathPhoto;

				// Bitmap bm = DecodeUtils.decode(ChatNewActivity.this,
				// Uri.parse(filePathPhoto), 800, 800);
				//
				// if (bm == null) {
				// Toast.makeText(ChatNewActivity.this, "Bạn chưa chọn ảnh!",
				// Toast.LENGTH_SHORT).show();
				// return;
				// }

				// ByteArrayOutputStream stream = new ByteArrayOutputStream();
				// bm.compress(Bitmap.CompressFormat.JPEG, 40, stream);
				// byteArray = stream.toByteArray();

				// upload image
				addMsgImage(filePathPhoto);

				try {
					if (cursor != null) {
						cursor.close();
					}
				} catch (IllegalStateException e) {
					e.printStackTrace();
				}

				break;
			case RESULT_CAPTURE_PHOTO:

				String[] projection = { MediaColumns.DATA };
				Cursor cursor1 = managedQuery(mCapturedImageURI, projection, null, null, null);
				int column_index_data = cursor1.getColumnIndexOrThrow(MediaColumns.DATA);
				cursor1.moveToFirst();
				String filePathCapture = cursor1.getString(column_index_data);
				Log.i("DATA", "File upload :" + filePathCapture);

				// Bitmap bm1 = DecodeUtils.decode(ChatNewActivity.this,
				// Uri.parse(filePathCapture), 800, 800);

				// if (bm1 == null) {
				// Toast.makeText(ChatNewActivity.this, "Bạn chưa chọn ảnh!",
				// Toast.LENGTH_SHORT).show();
				// return;
				// }

				// ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
				// bm1.compress(Bitmap.CompressFormat.JPEG, 40, stream1);
				// byteArray = stream1.toByteArray();

				addMsgImage("file://" + filePathCapture);

				try {
					if (cursor1 != null) {
						cursor1.close();
					}
				} catch (IllegalStateException e) {
					e.printStackTrace();
				}
				break;

			case RESULT_RECORD:
				String mpString = data.getStringExtra("mpString");
				addLinkAudio("" + mpString);
			}
		}
	}

	@SuppressLint("NewApi")
	public static int byteSizeOf(Bitmap bitmap) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			return bitmap.getAllocationByteCount();
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bitmap.getByteCount();
		} else {
			return bitmap.getRowBytes() * bitmap.getHeight();
		}
	}

	@Override
	@Deprecated
	public void startManagingCursor(Cursor c) {
		if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
			super.startManagingCursor(c);
		}
	}

	void uploadImage(final ObjMsgChat oMsg) {
		RequestParams params = new RequestParams();
		params.put("sso_id", preferenceHelper.getUserId());
		params.put("hash", preferenceHelper.getHash());

		String pathImg = oMsg.getUrlImageKH();
		Bitmap bm1 = DecodeUtils.decode(ChatNewActivity.this, Uri.parse(pathImg), 800, 800);

		if (bm1 == null) {
			Toast.makeText(ChatNewActivity.this, "Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
			return;
		}

		ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
		bm1.compress(Bitmap.CompressFormat.JPEG, 40, stream1);
		byte[] byteImg = stream1.toByteArray();

		params.put("picture", new ByteArrayInputStream(byteImg), "image.jpg");

		// Log.d("imagelog", ""+byteArray.length);

		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://vchat.vn/service/upload_image.php", params, new MyJsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Toast.makeText(ChatNewActivity.this, "Request failed.", Toast.LENGTH_SHORT).show();
				oMsg.setStatus(2);
				dbf.updateStatusMsg(oMsg.getMsgID(), oMsg.getStatus());
				updateListview();
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					String error = re.getString("error");

					if (!error.equals("")) {
						Log.i("DATA", "File qua lon");

						Toast.makeText(ChatNewActivity.this, "File ảnh quá lớn.", Toast.LENGTH_SHORT).show();
					} else {
						String data = re.getString("data");
						Log.i("DATA", "URL tra ve: " + data);
						sendMsgImage(data, oMsg);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

		});
	}

	void showProgressBar() {
		try {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					try {
						progressBar.setVisibility(View.VISIBLE);
					} catch (Exception e) {
					}
				}
			});
		} catch (Exception e) {
		}
	}

	void hiddenProgressBar() {
		try {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					try {
						progressBar.setVisibility(View.GONE);
					} catch (Exception e) {
					}
				}
			});
		} catch (Exception e) {
		}
	}

	void forceHiddenProgressBar() {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				hiddenProgressBar();
			}
		}, 60000);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		outState.putString("hash", hashChat + "");
		if (mCapturedImageURI != null) {
			outState.putString("uri", mCapturedImageURI.toString());
			Log.i("test", "onSaveInstanceState " + mCapturedImageURI);
		}

		super.onSaveInstanceState(outState);
	};

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		isLastestMsg = true;
		goToLastestMsg();
	}

	private void onOfSocket(String event, String jsondata) {

		Log.i("Socket", "onOfSocket");

		if (event.equals("chat")) {
			String json = jsondata;
			Log.i("vChat", json.toString());
			try {
				JSONObject jos = new JSONObject(json);

				JSONObject jo = jos.getJSONObject("data");

				int sendId = jo.getInt("send_id");
				final String name = jo.getString("name");
				final String content = jo.getString("text");
				final int time = jo.getInt("time");
				String type, urlImage;
				if (jo.has("type")) {
					type = jo.getString("type");
					urlImage = content;
					if (type.equals("image")) {
						type = "image";
						urlImage = content;
					} else {
						type = "text";
						urlImage = "";
					}

				} else {
					type = "text";
					urlImage = "";
				}

				String msgId = "";

				if (jo.has("vgc_key")) {
					msgId = String.valueOf(jo.getInt("vgc_key"));
				}

				// Log.e("Tuan", "vgc_key============" + msgId);

				if (msgId.equals("")) {
					msgId = time + "" + objKhachhang.getId();
				}

				final ObjMsgChat objMsgChat = new ObjMsgChat();
				objMsgChat.setUrlImageKH(urlImage);
				objMsgChat.setFromId(String.valueOf(sendId));
				objMsgChat.setContent(content);
				objMsgChat.setUrlAvatarKhachhang("");
				objMsgChat.setTenKhachHang(name);
				objMsgChat.setTime(time);
				objMsgChat.setType(type);
				objMsgChat.setMsgID(msgId);

				final ObjKhachhang oKh = new ObjKhachhang();
				oKh.setUrlAvatar("");
				oKh.setName(name);
				oKh.setAddress("");
				oKh.setDsDaxem("");
				oKh.setId(String.valueOf(sendId));
				oKh.setTxtWebsite("");
				oKh.setOnline(1);
				oKh.setUrlDangxem("");
				oKh.setTimeLastMessage(String.valueOf(time));
				oKh.setLastMessage(content);
				dbf.insertMSG(objMsgChat, objMsgChat.getFromId(), Common.SENDED, msgId, ChatNewActivity.this);
				Log.i("vChat", "Co o trong man hinh chat :" + Common.onScreenChat);

				if (Common.onScreenChat == true) {
					if (objKhachhang.getId().equals(oKh.getId())) {

						Mlog.w("On()+ objKhachhang.getId().equals(oKh.getId())");

						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// objMsgChats.addAll(db.getAllMsgHis(objKhachhang.getId()));
								updateListview();
								goToLastestMsg();
								objKhachhang.setLastMessage(content);
								objKhachhang.setTimeLastMessage("" + time);
								objKhachhang.setIsRead(0);
								db.updateHischat(objKhachhang);
							}
						});

					} else {
						Mlog.w("tin nhan khach chat objKhachhang.getId()" + objKhachhang.getId());

						Mlog.w("tin nhan khach chat oKh.getId()" + oKh.getId());

						llNewMsg.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View view) {

								Log.i("vChat", "Trong man hinh chat click new msg");
								ChatNewActivity.onShow = true;
								isNew = true;
								Intent t = new Intent(ChatNewActivity.this, ChatNewActivity.class);
								t.putExtra("khachhang", oKh);
								Log.i("Socket", "003");
								finish();
								startActivity(t);

							}
						});

						if (objKhachhang.getId().equals(oKh.getId()) || oKh.getId().equals(preferenceHelper.getAdminId()))
							return;

						oKh.setIsRead(1);
						db.updateHischat(oKh);

						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								showAnimationNewMsg();
								if (preferenceHelper.getSettingRingtone() == 1) {
									playRingtone();
								}
								txtTen.setText(oKh.getName());
								txtMsg.setText(oKh.getLastMessage());

							}
						});
					}
				} else {

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

	void addLinkAudio(String path) {
		String msgId = String.valueOf(Common.getCurrentTime() / 1000);
		// ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(),
		// "", "", url);
		ObjMsgChat objMsgChat = new ObjMsgChat(preferenceHelper.getAdminId(), "", "", path, preferenceHelper.getUserName(), preferenceHelper.getMyAvatar(),
				preferenceHelper.getLink());
		objMsgChat.setType(ObjMsgChat.TYPE_AUDIO);
		objMsgChat.setStatus(Common.SENDING);
		objMsgChat.setMsgID(msgId);
		objMsgChat.setUrlImageKH(path);
		// objMsgChat.setVgc_key(msgId);
		objMsgChat.setTime(Common.getCurrentTime() / 1000);

		dbf.insertMSG(objMsgChat, objKhachhang.getId(), Common.SENDING, msgId, ChatNewActivity.this);
		btnSend.setEnabled(false);
		mHandler.postDelayed(rEnableSend, 700);
		updateListview();
		uploadLinkAudio(objMsgChat);
	}

	private void uploadLinkAudio(ObjMsgChat objMsgChat) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		ObjMsgChat moj = (ObjMsgChat) arg0.getAdapter().getItem(arg2);
		if (ObjMsgChat.TYPE_AUDIO.equals(moj.getType())) {

			if (currSB != null) {
				currSB.setProgress(0);
				currTimePlay.setText(Utils.fomatTime(lastDuration));
				currBtnPlay.setImageResource(R.drawable.btn_playvideomsg_o);
			}
		} else
			return;

		currSB = (SeekBar) arg1.findViewById(R.id.sbMe);
		currTimePlay = (TextView) arg1.findViewById(R.id.tv_time_me);
		currBtnPlay = (ImageView) arg1.findViewById(R.id.btnPlay);
		if (curPosPlay == arg2) {
			stopPlay();
			return;
		}
		curPosPlay = arg2;

		playAudio(moj, arg2);
	}

	private void stopPlay() {
		curPosPlay = -1;
		if (currSB != null & currTimePlay != null & currBtnPlay != null) {
			currSB.setProgress(0);
			currTimePlay.setText(Utils.fomatTime(lastDuration));
			currBtnPlay.setImageResource(R.drawable.btn_playvideomsg_o);
		}
		if (mpVoice != null) {
			try {
				if (mpVoice.isPlaying())
					mpVoice.stop();
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

	}

	@Override
	public void callBack(Object value, int where) {
		switch (where) {
		case ChatAdapter.DELETATE_PLAY_AUDIO:
			int position = (Integer) value;
			// playAudio(position);
			// Toast.makeText(getBaseContext(), "" + position, 0).show();
			break;
		case ChatAdapter.DELEGATE_SHOW_IMAGE:

			Dl.showdialog((String) value, ChatNewActivity.this);
			break;

		default:
			break;
		}

	}

	private void playAudio(ObjMsgChat oj, int position) {
		// ObjMsgChat oj = (ObjMsgChat) listChat.getAdapter().getItem(position);
		currBtnPlay.setImageResource(R.drawable.btn_pausevideomsg_o);
		curPosPlay = position;
		Mlog.isLog = true;

		if (ObjMsgChat.TYPE_AUDIO.equals(oj.getType())) {
			String urlAudio = oj.getUrlImageKH();
			Log.i("audio", urlAudio);

			if (mpVoice != null) {
				try {
					if (mpVoice.isPlaying()) {

						mpVoice.stop();
						mpVoice.release();
					}
				} catch (Exception e) {

					Log.i("audio", "ko stop duoc em nhe");

				}
			}
			mpVoice = new MediaPlayer();
			try {
				mpVoice.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer arg0) {
						currBtnPlay.setImageResource(R.drawable.btn_playvideomsg_o);
						updateSeekBar();
						mpVoice.stop();
						mHandler.removeCallbacks(rUpdateSeekbar);
						currTimePlay.setText(Utils.fomatTime(mpVoice.getDuration()));
						currSB.setProgress(0);
						mpVoice.release();

					}
				});
				mpVoice.reset();
				mpVoice.setDataSource(ChatNewActivity.this, Uri.parse(urlAudio));
				mpVoice.prepare();
				mpVoice.start();
				adapter.curPostionPlay = position;
				// adapter.notifyDataSetChanged();
				int duaration = mpVoice.getDuration();
				currSB.setMax(duaration);
				mHandler.removeCallbacks(rUpdateSeekbar);
				mHandler.post(rUpdateSeekbar);
				lastDuration = mpVoice.getDuration();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {

				Toast.makeText(getBaseContext(), "Không tìm thấy file", 0).show();
				e.printStackTrace();
			}
		}

	}

}
